# -*- coding: UTF-8 -*-
from json import dumps
from Code.Model.sc_global import Global
from Code.Utils.sc_func import Common, Singleton


@Singleton
class Logger(object):

    def __init__(self):
        self.level_map = {'debug': 0, 'info': 1, 'warn': 2, 'error': 3}
        self.log_path = Global.G_LOG_PATH
        self.log_level = 'info'

    def _write_log(self, level, log):
        if self.level_map[self.log_level] > self.level_map[level]:
            return
        log = dumps({'Date': Common.get_time(), 'Level': level, 'Log': log})
        try:
            with open(self.log_path, 'a+') as f:
                f.write('{}\n'.format(log))
        except Exception:
            pass

    def change_level(self, level):
        if level not in self.level_map:
            return
        self.log_level = level

    def close(self, data=None):
        self.info('Bye...')
        if Common.file_size(self.log_path) > Global.G_LOG_SIZE:
            Common.remove('staged-{}'.format(self.log_path))
            Common.rename(self.log_path, 'staged-{}'.format(self.log_path))

    def info(self, log):
        self._write_log('info', log)

    def warn(self, log):
        self._write_log('warn', log)

    def error(self, log):
        self._write_log('error', log)

    def debug(self, log):
        self._write_log('debug', log)


logger = Logger()
